import { Controller } from 'egg';
import { Op } from 'sequelize';

export default class GoodsAttrController extends Controller {

  // 商品类型所有列表
  async all() {
    const result = await this.ctx.service.goods.type.findAll({ status: 1 }, '');

    if (result) {
      this.ctx.success({
        data: result
      });
    }
  }


  // 商品类型列表
  async list() {
    const { page, pageSize } = this.ctx.validateReq(
      'goods.type.list',
    ).query;

    const where = {};
    const result = await this.ctx.service.goods.type.index(page, pageSize, where);

    if (result) {
      this.ctx.success({
        data: result
      });
    }
  }


  // 新建商品类型
  async create() {
    const { body } = this.ctx.validateReq('goods.type.create');

    const isExist = await this.ctx.model.AttrKey.findOne({
      where: {
        name: body.name,
      }
    });

    if (isExist) {
      return this.ctx.failure({
        code: 30000,
        data: {
          name: body.name,
        },
      });
    }

    const result = await this.ctx.service.goods.type.create(body);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        },
        status: 201,
      });
    }
  }


  // 编辑商品类型
  async update() {

    const { body, params: { id } } = this.ctx.validateReq('goods.type.update');

    const isExist = await this.ctx.model.AttrKey.findOne({
      where: {
        id: { [Op.ne]: id },
        name: body.name,
      }
    });

    if (isExist) {
      return this.ctx.failure({
        code: 30010,
        data: {
          name: body.name,
        },
      });
    }

    const result = await this.ctx.service.goods.type.update(id, body);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        }
      });
    }
  }


  // 删除商品类型
  async destroy() {
    const { params: { id } } = this.ctx.validateReq('goods.type.destroy');

    const result = await this.ctx.service.goods.type.destroy(id);

    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        }
      });
    }
  }

}
